//
//  NewsTableViewController.m
//  老司机发车了
//
//  Created by 程成 on 16/8/6.
//  Copyright © 2016年 斌. All rights reserved.
//

#import "FirstNewsTableViewController.h"
#import "CarouselModel.h"
#import "FirstNewsModel.h"
#import "FirstNews1TableViewCell.h"
#import "FirstNews2TableViewCell.h"
#import "SpecialTableViewController.h"
#import "DetailCellViewController.h"

@interface FirstNewsTableViewController ()<ZXRollViewDelegate>
/*轮播图数组*/
@property (strong, nonatomic )NSMutableArray *carouselArray;
@property (nonatomic, strong)ZXRollView *scrollView;
/*imgV1*/
@property (strong, nonatomic )UIImageView *imgV1;
/*imgV1*/
@property (strong, nonatomic )UIImageView *imgV2;
/*imgV1*/
@property (strong, nonatomic )UIImageView *imgV3;
/*imgV1*/
@property (strong, nonatomic )UIImageView *imgV4;
/*imgV1*/
@property (strong, nonatomic )UIImageView *imgV5;
/*Label*/
@property (strong, nonatomic )UILabel *label1;
/*Label*/
@property (strong, nonatomic )UILabel *label2;
/*Label*/
@property (strong, nonatomic )UILabel *label3;
/*Label*/
@property (strong, nonatomic )UILabel *label4;
/*Label*/
@property (strong, nonatomic )UILabel *label5;

/*news*/
@property (strong, nonatomic )NSMutableArray *newsArray;
//
@property (nonatomic, assign)NSInteger start;
@property (nonatomic, assign)NSInteger limit;
@end

@implementation FirstNewsTableViewController
- (UILabel *)label1{
    if (!_label1) {
        _label1 = [[UILabel alloc] initWithFrame:CGRectMake(5, 0,self.view.bounds.size.width, 20)];
        _label1.font = [UIFont systemFontOfSize:13];
        _label1.backgroundColor = [UIColor grayColor];
        _label1.alpha = 0.8;
        _label1.textColor = [UIColor whiteColor];
    }
    return _label1;
}
- (UILabel *)label2{
    if (!_label2) {
        _label2 = [[UILabel alloc] initWithFrame:CGRectMake(5, 0,self.view.bounds.size.width, 20)];
        _label2.font = [UIFont systemFontOfSize:13];
        _label2.backgroundColor = [UIColor grayColor];
        _label2.alpha = 0.8;
        _label2.textColor = [UIColor whiteColor];
    }
    return _label2;
}
- (UILabel *)label3{
    if (!_label3) {
        _label3 = [[UILabel alloc] initWithFrame:CGRectMake(5, 0,self.view.bounds.size.width, 20)];
        _label3.font = [UIFont systemFontOfSize:13];
        _label3.backgroundColor = [UIColor grayColor];
        _label3.alpha = 0.8;
        _label3.textColor = [UIColor whiteColor];
    }
    return _label3;
}
- (UILabel *)label4{
    if (!_label4) {
        _label4 = [[UILabel alloc] initWithFrame:CGRectMake(5, 0,self.view.bounds.size.width, 20)];
        _label4.font = [UIFont systemFontOfSize:13];
        _label4.backgroundColor = [UIColor grayColor];
        _label4.alpha = 0.8;
        _label4.textColor = [UIColor whiteColor];
    }
    return _label4;
}
- (UILabel *)label5{
    if (!_label5) {
        _label5 = [[UILabel alloc] initWithFrame:CGRectMake(5, 0,self.view.bounds.size.width, 20)];
        _label5.font = [UIFont systemFontOfSize:13];
        _label5.backgroundColor = [UIColor grayColor];
        _label5.alpha = 0.8;
        _label5.textColor = [UIColor whiteColor];
    }
    return _label5;
}
- (UIImageView *)imgV1{
    if (!_imgV1) {
        _imgV1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 180)];
        _imgV1.userInteractionEnabled = YES;
    }
    return _imgV1;
}
- (UIImageView *)imgV2{
    if (!_imgV2) {
        _imgV2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 180)];
        _imgV2.userInteractionEnabled = YES;
    }
    return _imgV2;
}
- (UIImageView *)imgV3{
    if (!_imgV3) {
        _imgV3 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 180)];
        _imgV3.userInteractionEnabled = YES;
    }
    return _imgV3;
}
- (UIImageView *)imgV4{
    if (!_imgV4) {
        _imgV4 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 180)];
        _imgV4.userInteractionEnabled = YES;
    }
    return _imgV4;
}
- (UIImageView *)imgV5{
    if (!_imgV5) {
        _imgV5 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 180)];
        _imgV5.userInteractionEnabled = YES;
    }
    return _imgV5;
}
- (NSMutableArray *)carouselArray{
    if (!_carouselArray) {
        _carouselArray = [[NSMutableArray alloc] init];
    }
    return _carouselArray;
}
- (NSMutableArray *)newsArray{
    if (!_newsArray) {
        _newsArray = [[NSMutableArray alloc] init];
    }
    return _newsArray;
}
- (void)analyseData{
    [NetWorkRequestManager requestWithType:GET urlString:FirstNewsUrl parDic:@{} finish:^(NSData *data) {
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        if (_start == 0) {
            [self.newsArray removeAllObjects];
        }
        for (NSDictionary *dic in dictionary[@"T1348647909107"][0][@"ads"]) {
            CarouselModel *model = [[CarouselModel alloc ] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.carouselArray addObject:model];
        }
        for (NSDictionary *dic in dictionary[@"T1348647909107"]) {
            FirstNewsModel *model = [[FirstNewsModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.newsArray addObject:model];
        }
        [self.newsArray removeObjectAtIndex:0];

        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            //结束刷新(在表视图刷新完毕之后)
            [self.tableView.mj_header endRefreshing];
        });
        //结束加载
        [self.tableView.mj_footer endRefreshing];
    } finishError:^(NSError *error) {
        NSLog(@"数据解析出错");
    }];
}

- (void)analysePullupRefresh{
    NSString *url = [NSString stringWithFormat:FirstRefreshUrl,_start];
    [NetWorkRequestManager requestWithType:GET urlString:url parDic:@{@"start":@(_start),@"limit":@(_limit)} finish:^(NSData *data) {
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        if (_start == 0) {
            [self.newsArray removeAllObjects];
        }
        for (NSDictionary *dic in dictionary[@"T1348647909107"][0][@"ads"]) {
            CarouselModel *model = [[CarouselModel alloc ] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.carouselArray addObject:model];
        }
        for (NSDictionary *dic in dictionary[@"T1348647909107"]) {
            FirstNewsModel *model = [[FirstNewsModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.newsArray addObject:model];
        }
        [self.newsArray removeObjectAtIndex:0];

        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            //结束刷新(在表视图刷新完毕之后)
            [self.tableView.mj_header endRefreshing];
        });
        //结束加载
        [self.tableView.mj_footer endRefreshing];
    } finishError:^(NSError *error) {
        NSLog(@"数据解析出错");
    }];
}
//下拉刷新
- (void)pullDownHeader{
    //开始下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _start = 0;
        [self analyseData];
    }];
    //开始上拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.start = _start += 20;
        [self analysePullupRefresh];
    }];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self analyseData];
    [self pullDownHeader];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"FirstNews1TableViewCell" bundle:nil] forCellReuseIdentifier:@"fn1Cell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"FirstNews2TableViewCell" bundle:nil] forCellReuseIdentifier:@"fn2Cell"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else
        return self.newsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 180)];
        self.scrollView = [[ZXRollView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 180)];
        self.scrollView.pageIndicatorImage = [UIImage imageNamed:@"indicatorImageNormal"];
        self.scrollView.currentPageIndicatorImage = [UIImage imageNamed:@"indicatorImageHighlight"];
        self.scrollView.autoRollingTimeInterval = M_LN10;
        self.scrollView.delegate = self;
        [self.scrollView reloadViews];
        [view addSubview:_scrollView];
        [cell addSubview:view];
        return cell;
    }else{
        FirstNewsModel *model = self.newsArray[indexPath.row];
        if (![model.boardid isEqualToString:@"photoview_bbs"]) {
            FirstNews1TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"fn1Cell"];
            if (!cell) {
                cell = [[FirstNews1TableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"fn1Cell"];
            }
            [cell setValueWithModel1:model];
            if (![model.skipType isEqualToString:@"special"]) {
                cell.specialLabel.backgroundColor = [UIColor whiteColor];
            }else{
                cell.specialLabel.backgroundColor = [UIColor redColor];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else{
            FirstNews2TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"fn2Cell"];
            if (!cell) {
                cell = [[FirstNews2TableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"fn2Cell"];
            }
            [cell setValueWithModel2:model];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    FirstNewsModel *model = self.newsArray[indexPath.row];
    DetailCellViewController *detailVC = [[DetailCellViewController alloc] init];
    if ([model.skipType isEqualToString:@"special"]) {
        SpecialTableViewController *specialVC = [[SpecialTableViewController alloc] init];
        specialVC.specialid = model.skipID;
        [self.navigationController pushViewController:specialVC animated:YES];
    }else if([model.boardid isEqualToString:@"photoview_bbs"]){
        detailVC.skipid = model.skipID;
        detailVC.index = 1;
        detailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detailVC animated:YES];
    }else{
        detailVC.urlString = model.url_3w;
        detailVC.index = 2;
        detailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 180;
    }else{
        FirstNewsModel *model = self.newsArray[indexPath.row];
        if (![model.boardid isEqualToString:@"photoview_bbs"]) {
            return 100;
        }else{
            return 120;
        }
    }
}
#pragma mark------------轮播代理---------------
- (NSInteger)numberOfItemsInRollView:(ZXRollView *)rollView{
    return self.carouselArray.count;
}
- (void)rollView:(ZXRollView *)rollView setViewForRollView:(UIView *)view atIndex:(NSInteger)index{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    switch (index) {
        case 0:{
            [self.imgV1 sd_setImageWithURL:[NSURL URLWithString:((CarouselModel *)_carouselArray[0]).imgsrc]];
            self.label1.text = ((CarouselModel *)_carouselArray[0]).title;
            [_imgV1 addSubview:_label1];
            [_imgV1 addGestureRecognizer:tap];
            _imgV1.tag = 1;
            [view addSubview:_imgV1];
        }
            break;
        case 1:{
            [self.imgV2 sd_setImageWithURL:[NSURL URLWithString:((CarouselModel *)_carouselArray[1]).imgsrc]];
            self.label2.text = ((CarouselModel *)_carouselArray[1]).title;
            [_imgV2 addSubview:_label2];
            [_imgV2 addGestureRecognizer:tap];
            _imgV2.tag = 2;
            [view addSubview:_imgV2];
        }
            break;
        case 2:{
            [self.imgV3 sd_setImageWithURL:[NSURL URLWithString:((CarouselModel *)_carouselArray[2]).imgsrc]];
            self.label3.text = ((CarouselModel *)_carouselArray[2]).title;
            [_imgV3 addSubview:_label3];
            [_imgV3 addGestureRecognizer:tap];
            _imgV3.tag = 3;
            [view addSubview:_imgV3];
        }
            break;
        case 3:{
            [self.imgV4 sd_setImageWithURL:[NSURL URLWithString:((CarouselModel *)_carouselArray[3]).imgsrc]];
            self.label4.text = ((CarouselModel *)_carouselArray[3]).title;
            [_imgV4 addSubview:_label4];
            [_imgV4 addGestureRecognizer:tap];
            _imgV4.tag = 4;
            [view addSubview:_imgV4];
        }
            break;
        case 4:{
            [self.imgV5 sd_setImageWithURL:[NSURL URLWithString:((CarouselModel *)_carouselArray[4]).imgsrc]];
            self.label5.text = ((CarouselModel *)_carouselArray[4]).title;
            [_imgV5 addSubview:_label5];
            [_imgV5 addGestureRecognizer:tap];
            _imgV5.tag = 5;
            [view addSubview:_imgV5];
        }
            break;
        default:
            break;
    }
}
- (void)tapAction:(UITapGestureRecognizer *)tap{
    UIView *view = tap.view;
    NSInteger index = view.tag - 1;
    CarouselModel *model = self.carouselArray[index];
    DetailCellViewController *detailVC = [[DetailCellViewController alloc] init];
    detailVC.skipid = model.url;
    detailVC.index = 1;
    detailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}
- (void)dealloc{
    [self.scrollView invalidate];
}

@end
